"""
用户相关Schemas
"""
from typing import Optional
from pydantic import EmailStr, Field, validator

from app.schemas.base import BaseSchema, TimeStampSchema
from app.models.user import UserRole, UserStatus


# ==================== 用户注册 ====================

class UserRegister(BaseSchema):
    """用户注册请求"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    password: str = Field(..., min_length=8, max_length=32, description="密码")
    email: Optional[EmailStr] = Field(None, description="邮箱")
    phone: Optional[str] = Field(None, min_length=11, max_length=11, description="手机号")
    full_name: Optional[str] = Field(None, max_length=100, description="真实姓名")
    
    @validator('username')
    def username_alphanumeric(cls, v):
        """用户名必须是字母数字"""
        if not v.replace('_', '').isalnum():
            raise ValueError('用户名只能包含字母、数字和下划线')
        return v


# ==================== 用户登录 ====================

class UserLogin(BaseSchema):
    """用户登录请求"""
    username: str = Field(..., description="用户名/邮箱/手机号")
    password: str = Field(..., description="密码")


class TokenResponse(BaseSchema):
    """Token响应"""
    access_token: str = Field(..., description="访问令牌")
    refresh_token: str = Field(..., description="刷新令牌")
    token_type: str = Field(default="bearer", description="令牌类型")
    expires_in: int = Field(..., description="过期时间（秒）")


# ==================== 用户信息 ====================

class UserBase(BaseSchema):
    """用户基础信息"""
    username: str
    email: Optional[str] = None
    phone: Optional[str] = None
    full_name: Optional[str] = None
    avatar: Optional[str] = None
    role: UserRole
    status: UserStatus
    is_vip: bool = False


class UserDetail(UserBase, TimeStampSchema):
    """用户详细信息"""
    id: int
    points: str = "0"
    login_count: str = "0"
    last_login_at: Optional[str] = None
    vip_expire_at: Optional[str] = None


class UserUpdate(BaseSchema):
    """用户更新请求"""
    full_name: Optional[str] = Field(None, max_length=100)
    avatar: Optional[str] = Field(None, max_length=255)
    email: Optional[EmailStr] = None
    phone: Optional[str] = Field(None, min_length=11, max_length=11)


class PasswordChange(BaseSchema):
    """修改密码请求"""
    old_password: str = Field(..., description="旧密码")
    new_password: str = Field(..., min_length=8, max_length=32, description="新密码")


class PasswordReset(BaseSchema):
    """重置密码请求"""
    email: EmailStr = Field(..., description="注册邮箱")
    code: str = Field(..., min_length=6, max_length=6, description="验证码")
    new_password: str = Field(..., min_length=8, max_length=32, description="新密码")


# ==================== 用户列表 ====================

class UserListResponse(BaseSchema):
    """用户列表响应"""
    total: int
    page: int
    page_size: int
    users: list[UserDetail]







